<template>
  <q-page class="q-pa-md" v-loading="loading">
    <div style="position: relative; ">
      <q-breadcrumbs class="q-mb-md" style="height:50px;line-height: 40px; border-bottom: 1px dashed #ccc;">
        <q-breadcrumbs-el label="模型仓库" icon="bi-folder2-open" />
        <q-breadcrumbs-el label="模型创建" icon="bi-people" />
      </q-breadcrumbs>
    </div>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="140px"
      class="demo-ruleForm typeBox"
      style="max-width: 45%;" status-icon>
      <el-form-item label="模型名称：" prop="title">
        <el-input v-model.trim="ruleForm.title" placeholder="请选择模型名称" maxlength="25" show-word-limit/>
      </el-form-item>
      <el-form-item label="版本：" prop="version_number">
        <el-input v-model.trim="ruleForm.version_number" disabled />

      </el-form-item>
      <el-form-item label="描述：" prop="description">
        <el-input v-model.trim="ruleForm.description" type="textarea" />
      </el-form-item>
      <el-form-item label="选择算法：" prop="modelId">
        <el-select v-model.trim="ruleForm.modelId" placeholder="请选择算法">
          <el-option v-for="item in allAlg" :key="item.title" :label="item.title" :value="item.id" @click="chooseAlg" />
        </el-select>
      </el-form-item>
      <el-form-item label="选择训练作业：" prop="model_run_id" v-if="ruleForm.modelId && modelRunsData.length > 0">
        <el-select v-model.trim="ruleForm.model_run_id" placeholder="请选择训练作业" prop="model_run_id">
          <el-option v-for="item in modelRunsData" :key="item.title" :label="item.title" :value="item.id" />
        </el-select>
      </el-form-item>
      <p v-if="ruleForm.modelId && modelRunsData.length ===0" style="color: orangered;margin-left: 50px">该算法下没有对应的训练任务,请先选择创建训练任务。</p>
    </el-form>
    <div class="row" style="position:absolute;right: 50px;bottom:50px">
      <el-button @click="resetForm(ruleFormRef)" size="small">取消</el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)" size="small">
        完成创建
      </el-button>
    </div>
  </q-page>
</template>

<script setup lang="ts">
import { ref, reactive, shallowRef, toRaw } from 'vue';
import { useRouter } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus'
import {createModelData, getAlgAllList, getModelAboutRuns, createModelApp, validateModelName} from 'src/api/model'
import { ElMessage } from 'element-plus'
import {modelStore} from "stores/model";
const router = useRouter()
const loading = ref(false)
const projectId = router.currentRoute.value.params.project_id;
const ruleFormRef = ref<FormInstance>()
interface useInfoModel {
  title: string;
  description: string;
  modelId?:string;
  version_number: string;
  model_run_id: string
}
const ruleForm = reactive<useInfoModel>({
  title: '',
  description: '',
  version_number: '1',
  modelId:'',
  model_run_id: ''
})
// validator: validateUsernameChange,
const validateTitle = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('模型名称不能为空'))
    return
  }
  let params = {
    title: ruleForm.title
  }
  validateModelName(projectId,params).then( res =>{
    if( res.data.exists ){
      callback(new Error('模型名称重复'))
    }
    callback()
  }).catch(err =>{
    callback(new Error('校验接口报错'))
  })
}

const rules = reactive<FormRules>({
  title: [
    { required: true, validator: validateTitle, trigger: 'blur' }
  ],
  modelId: [
    { required: true, message: '请选择算法' },
  ],
  model_run_id: [
    { required: true, message: '请选择训练作业' },
  ],
})

function createModelFun(){
  createModelData(projectId,ruleForm).then((res)=>{
    console.log(res)
  }).finally(()=>{
    console.log('success')
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  router.push({ name: 'model-app', params: { project_id: projectId } })
}

const postForm=reactive({
  title: "测试数据",
  git_version: "版本",
  modelData: "部署类型",
  description: "描述描述",
  git_modelManage: ''
})




//存放获取所有的算法
const allAlg = shallowRef([
  {
    title: '',
    id: ''
  }
])
//存放获取所有的训练任务
const modelRunsData = shallowRef([])
AlgAllList();//获取所有的算法
function AlgAllList() {
  getAlgAllList(projectId).then((res: any) => {
    allAlg.value = Object.assign(res.data)
  }).catch(error => {
    console.log(error)
  })
}

//获取算法对应下的训练任务
function chooseAlg() {
  loading.value = true;
  getModelAboutRuns(projectId, ruleForm.modelId).then((res: any) => {
    loading.value = false;
    modelRunsData.value = Object.assign(res.data)
  }).finally(() => {
    loading.value = false;
  }).catch(error => {
    console.log(error)
  })
}
//点击创建模型
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let params = Object.assign(ruleForm);
      createModelApp(projectId,params).then((res: any) => {
        ElMessage.success(`创建模型成功！`);
        formEl.resetFields();//清空表单
        router.push({ name: 'model-app', params: { project_id: projectId } })
      }).finally(() => {
        loading.value = false;
      }).catch( (error:any) => {
        ElMessage.success(`模型创建失败,提示${error.data}！`)
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>

<style scoped lang="scss">
.labelTypeBox {
  .el-radio-button {
    margin-right: 20px;
    margin-bottom: 20px;

    // 自定义单选框样式
    &::v-deep .el-radio-button__inner {
      border-radius: 4px;
      border-left: 1px solid #dcdfe6;
    }

    &::v-deep .el-radio-button__original-radio:checked+.el-radio-button__inner {
      background-color: white;
      color: #3D5CE4;
      border-color: #3D5CE4;
      border-left: 1px solid #3D5CE4;
      box-shadow: none;
    }
  }

}

.labelTypeBoxText,
.labelTypeBoxData {
  width: 70vw;

  .el-image {
    width: 100px;
    height: 80px;
  }

  .el-radio-button {
    margin-right: 20px;

    // 自定义单选框样式
    &::v-deep .el-radio-button__inner {
      border-radius: 4px;
      border-left: 1px solid #dcdfe6;
      font-size: 12px;
    }
  }
}
::v-deep .el-form-item__label {
  color: #1D1D1D;
}
</style>
